package controller;

import common.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
import ui.Main;
import util.IsNumber;
import util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ResourceBundle;

public class DoHomeworkController implements Initializable {
    @FXML
    private ListView<String> questionlist;//题目列表
    private ObservableList<String> source= FXCollections.observableArrayList();//数据源
    private Topic topic;
    @FXML
    private Label title;
    private Homework homework;
    private boolean flag=false;
    private int type;
    public DoHomeworkController(Topic topic,int type){
        this.type=type;
        this.topic=topic;
        source.addAll(topic.getQuestion());
        if(topic.getHomework()!=null){
            homework=topic.getHomework();
            flag=true;//表示已提交
        }else {
            homework=new Homework();
            homework.setAssignmentid(topic.getTopicid());
            homework.setStudentid(Main.userClientService.getUser().getId());
            homework.setStudentnumber(Main.userClientService.getUser().getNumber());
            homework.setStudentname(Main.userClientService.getUser().getName());
            for(int i=0;i<topic.getQuestion().size();i++){
                homework.getAnswers().add(new Answer());
                homework.getAnswers().get(i).setQuestion(topic.getQuestion().get(i));
            }
        }
        homework.setTeacherid(topic.getCourse().getTeacherId());
    }
    @Override
    public void initialize(URL location, ResourceBundle resources){
        title.setText(topic.getTitle());
        questionlist.setItems(source);
        questionlist.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(javafx.scene.control.ListView<String> param) {
                return new ListCell<String>() {
                    @Override
                    protected void updateItem(String str, boolean empty) {
                        super.updateItem(str, empty);
                        if (empty || str == null) {
                            setText(null);
                        } else {
                            setText("第"+(getIndex()+1)+"题");
                        }
                    }
                };
            }
        });
        questionlist.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                // 获取双击时选中的项
                String selectedItem = questionlist.getSelectionModel().getSelectedItem();
                if (selectedItem==null) return;
                description.setText(selectedItem);
                content.setText(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getContent());
                if(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getPic()!=null)
                    picPath.setText(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getPic().getFilename());
                else picPath.setText("null");
                if(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getFile()!=null)
                    filePath.setText(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getFile().getFilename());
                else filePath.setText("null");
                if(flag)
                    score.setText(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getScore());
            }
        });
        LocalDateTime dead=LocalDateTime.parse(topic.getDeaddate()+"T"+topic.getDeadtime());
        score.setVisible(false);
        if(dead.compareTo(LocalDateTime.now())<=0||flag){
            saveButton.setVisible(false);
            submitButton.setVisible(false);
            upFileButton.setVisible(false);
            upPicButton.setVisible(false);
            score.setVisible(true);
        }
        setVisible(type);
    }
    @FXML
    private Button saveButton,submitButton,upFileButton,upPicButton,downloadPicButton,downloadFileButton,finish,ok;
    @FXML
    private TextField score;
    public void setVisible(int type){
        if(type==1){
            //老师批改作业
            saveButton.setVisible(false);
            submitButton.setVisible(false);
            upPicButton.setVisible(false);
            upFileButton.setVisible(false);
        }else if(type==2){
            //学生查看作业
            downloadFileButton.setVisible(false);
            downloadPicButton.setVisible(false);
            finish.setVisible(false);
            ok.setVisible(false);
        }
    }
    @FXML
    private TextArea description;
    @FXML
    private TextArea content;
    @FXML
    private Label picPath;
    @FXML
    private Label filePath;
    @FXML
    public void save(){
        homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).setContent(content.getText());
        homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).setFile(file);
        homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).setPic(pic);
    }
    private FileRedefined pic=null;
    @FXML
    public void upPic()throws Exception{
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择图片");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); // 设置初始目录
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("图像文件", "*.png", "*.jpg", "*.gif")
        );
        File selectedFile = fileChooser.showOpenDialog(new Stage());
        if (selectedFile != null) {
            // 处理选定的文件
            picPath.setText(selectedFile.getName());
            pic=new FileRedefined(selectedFile.getName(), StreamUtils.streamToByteArray(new FileInputStream(selectedFile.getAbsoluteFile())));
            System.out.println("选定的文件: " + selectedFile.getAbsolutePath());
        }else{
            picPath.setText("null");
        }
    }
    private FileRedefined file=null;
    @FXML
    public void upFile()throws Exception{
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); // 设置初始目录
        File selectedFile = fileChooser.showOpenDialog(new Stage());
        if (selectedFile != null) {
            // 处理选定的文件
            filePath.setText(selectedFile.getName());
            file=new FileRedefined(selectedFile.getName(), StreamUtils.streamToByteArray(new FileInputStream(selectedFile.getAbsoluteFile())));
            System.out.println("选定的文件: " + selectedFile.getAbsolutePath());
        }else{
            filePath.setText("null");
        }
    }
    @FXML
    public void submit(){
        Socket socket= Main.userClientService.getSocket();
        try {
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            Message ms=new Message();
            ms.setState(MessageType.Submit_Work);
            oos.writeObject(ms);
            oos.writeObject(homework);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @FXML
    public void downloadPic(){
        if(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getPic()==null) return;
        //下载图片
        pic=homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getPic();
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择文件下载目录");
        File selectedDirectory = directoryChooser.showDialog(new Stage());
        if (selectedDirectory != null) {
            System.out.println("Selected directory: " + selectedDirectory.getAbsolutePath());
            // 在此执行您的下载操作，使用选择的目录
            StreamUtils.byteArrayToStream(pic.getContent(),selectedDirectory.getAbsolutePath()+"\\"+pic.getFilename());
        }
    }
    @FXML
    public void downloadFile(){
        if(homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getFile()==null) return;
        //下载附件
        file=homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).getFile();
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择文件下载目录");
        File selectedDirectory = directoryChooser.showDialog(new Stage());
        if (selectedDirectory != null) {
            System.out.println("Selected directory: " + selectedDirectory.getAbsolutePath());
            // 在此执行您的下载操作，使用选择的目录
            StreamUtils.byteArrayToStream(file.getContent(),selectedDirectory.getAbsolutePath()+"\\"+file.getFilename());
        }
    }
    @FXML
    public void finishCheck(){
        //完成批阅
        Socket socket= Main.userClientService.getSocket();
        try {
            ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
            Message ms=new Message();
            ms.setState(MessageType.Correct_HW);
            oos.writeObject(ms);
            double total=0.0;
            for(Answer t:homework.getAnswers()){
                total+=Double.parseDouble(t.getScore());
            }
            homework.setScore(Double.toString(total));
            oos.writeObject(homework);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @FXML
    public void ok(){
        //给某题打分
        if(IsNumber.isNumeric(score.getText()))
            homework.getAnswers().get(questionlist.getSelectionModel().getSelectedIndex()).setScore(score.getText());
        else
            score.setText("0");
    }
}
